package logic

import (
	"context"
	"errors"
	"manuscript-service/models/mysql"

	"manuscript-service/servicerpc/internal/svc"
	"manuscript-service/servicerpc/servicerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ServiceAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewServiceAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ServiceAddLogic {
	return &ServiceAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加
func (l *ServiceAddLogic) ServiceAdd(in *servicerpc.ServiceAddRequest) (*servicerpc.ServiceAddResponse, error) {
	// todo: add your logic here and delete this line
	//开启事务
	begin := mysql.DB.Begin()
	//添加时类别是否已经存在
	class := mysql.Class{
		Name: in.ClassName,
	}

	if err := class.FindClassByName(begin, in.ClassName); err != nil {
		begin.Rollback()
		return nil, err
	}
	//稿件名称查重
	var findService mysql.Service

	if err := findService.FindService(begin, in.Title); err == nil {
		begin.Rollback()
		return nil, errors.New("稿件名称重复了，请勿重复添加")
	}
	//简单添加
	service := mysql.Service{
		Title:     in.Title,
		Image:     in.Image,
		LikeCount: int(in.LikeCount),
		ClassId:   int(class.ID),
	}

	if err := service.ServiceAdd(begin); err != nil {
		begin.Rollback() //回滚
		return nil, err
	}
	begin.Commit() //提交
	return &servicerpc.ServiceAddResponse{
		ServiceId: int64(service.ID),
	}, nil
}
